<template>
	<view class="create-page">
		<hsb-business-evaluate-card
			ref="evaluateCardCom"
			:evInfo="evaluateInfo"
			:discountInfo="discountInfo.selected"
			:priceHistory="priceHistory"
			@evaluate="afreshEvaluate"
			@prices-explain="$refs.recycleWayFormCom.openPricesExplain()"
		/>
		<hsb-business-recycle-way-form
			ref="recycleWayFormCom"
			:account.sync="account"
			:accountName.sync="accountName"
			:phoneNumber.sync="phoneNumber"
			:evInfo="evaluateInfo"
			:creditInfo="creditInfo"
			:discountInfo="discountInfo.selected"
			:priceHistory="priceHistory"
			:productSkuList="productSkuList"
			:recycleList="recycleWays"
			:singleShareInfo="singleShareInfo"
			:selectRecycle="selectRecycle"
			:selectAddressInfo="addressInfo.selected"
			:selectDateInfo="dateInfo.selected"
			:storeInfo="currentStore"
			@recycle-change="recycleChange"
			@date-change="dateChange"
			@address-book="addressChange"
			@address="manageAddress"
			@store="chooseStore"
			@open-credit="beforeOpenCredit"
			@change-prepay="beforeChangePrepay"
		/>
		<hsb-business-place-order-tabbar
			:evInfo="evaluateInfo"
			:discountInfo="discountInfo.selected"
			@submit="checkPlaceOrderParams"
		/>
		<hsb-common-base-picker
			ref="datePickerCom"
			:list="dateInfo.list"
			columnName="time"
			childName="value"
			@confirm="chooseDate"
		/>
		<hsb-business-recycle-address
			ref="recycleAddressCom"
			:list="addressInfo.list"
			:selectRecycle="selectRecycle"
			@choose="chooseAddress"
			@add="manageAddress"
			@edit="manageAddress"
		/>
		<hsb-common-base-confirm
			ref="baseConfirmComp"
			title="提示"
			:content="evaluateErrMsg"
			contentAlign="center"
			:showCancel="false"
			confirmText="重新估价"
			@confirm="afreshEvaluate"
		/>
	</view>
</template>

<script>
import { mapState } from 'vuex'
import queryString from 'query-string'
// #ifdef MP-ALIPAY
import credit from '@/mixins/credit'
// #endif
import { recycleList } from '@/config'
import { computedDistance } from '@/utils'

export default {
	// #ifdef MP-ALIPAY
	mixins: [credit],
	// #endif
	computed: {
		...mapState({
			userLocation: state => state.userLocation,
			userSelectLocation: state => state.userSelectLocation
		})
	},
	data () {
		return {
			productId: '',
			evaluateId: '',
			account: '',
			accountName: '',
			phoneNumber: '',
			evaluateInfo: {},
			// #ifndef MP-ALIPAY
			creditInfo: {},
			// #endif
			evaluateErrMsg: '',
			selectRecycle: {},
			currentStore: {},
			recycleWays: [],
			priceHistory: [],
			productSkuList: [],
			singleShareInfo: {},
			bulletInfo: {},
			loading: false,
			dateInfo: {
				recycleWay: '',
				list: [],
				all: {
					sf: [],
					store: [],
					visit: [],
					sxx: []
				},
				selected: {
					sf: [],
					store: [],
					visit: [],
					sxx: []
				}
			},
			addressInfo: {
				recycleWay: '',
				list: [],
				all: {
					sf: [],
					store: [],
					visit: [],
					sxx: []
				},
				selected: {
					sf: {},
					store: {},
					visit: {},
					sxx: {}
				}
			},
			discountInfo: {
				recycleWay: '',
				list: [],
				all: {
					sf: [],
					store: [],
					visit: [],
					sxx: []
				},
				selected: {
					addConpous: {},
					useConpous: {}
				}
			}
		}
	},
	methods: {
		initData () {
			if (!this.evaluateId) {
				return uni.showToast({
					title: '估价ID缺失',
					icon: 'none'
				})
			}
			this.getEvaluateResult()
			this.getServiceTime()
		},
		/*
		 * 估价结果
		*/
		async getEvaluateResult () {
			const [res] = await this.$apis.getEvaluateResult({
				evaluateid: this.evaluateId
			})
			if (res._errCode === '0') {
				// res._data.typeActivityList = [
				// 	{
				// 		activityId: '1',
				// 		recycleType: '1',
				// 		couponMoney: '10000',
				// 		activityEndDate: "2023-11-20 00:00:00"
				// 	},
				// 	{
				// 		activityId: '2',
				// 		recycleType: '2',
				// 		couponMoney: '20000',
				// 		activityEndDate: "2023-11-20 00:00:00"
				// 	},
				// 	{
				// 		activityId: '3',
				// 		recycleType: '3',
				// 		couponMoney: '30000',
				// 		activityEndDate: "2023-11-20 00:00:00"
				// 	}
				// ]
				this.evaluateInfo = res._data || {}
				this.getSupportRecycleInfo()
				this.getPriceHistory()
			} else {
				this.evaluateErrMsg = res._errStr || '获取估价信息失败'
				this.$refs.baseConfirmComp.open()
			}
		},
		/*
		 * 回收方式
		 * 包含顺丰邮寄、工程师上门、到店回收
		*/
		async getServiceTime () {
			const [res] = await this.$apis.getServiceTime()
			if (res._errCode === '0') {
				const { xz = [], sf = [], sxx = [] } = res._data || {}
				this.dateInfo.all = {
					sf,
					store: xz,
					visit: xz,
					sxx
				}
			}
		},
		/*
		 * 回收方式
		 * 包含顺丰邮寄、工程师上门、到店回收
		*/
		async getSupportRecycleInfo () {
			const [res] = await this.$apis.getSupportRecycleInfo({
				evaluateId: this.evaluateInfo.evaluateid || this.evaluateId
			})
			if (res._errCode === '0') {
				const recycleWayInfo = res._data || {}
				const defaultRecycleWay = recycleWayInfo.defaultWay || ''
				const recycleWayList = recycleWayInfo.recycleWay || []
				this.recycleWays = recycleWayList.map(way => recycleList.find(item => item.recycleWay === way))
				this.selectRecycle = this.recycleWays.find(item => item.recycleWay === defaultRecycleWay) || this.recycleWays[0] || {}
				if (recycleWayList.includes('1')) {
					this.getStoreList()
				}
				this.getAllowCouponList()
				await this.getAllowAddressList()
				// #ifdef MP-ALIPAY
				this.checkCredit()
				// #endif
				this.getEvaluateSkuResult()
				this.getBulletInfo()
				this.getShareInfo()
			}
		},
		/*
		 * 用户地址
		 * 包含顺丰邮寄、工程师上门、到店回收
		*/
		async getAllowCouponList () {
			const params = {
				productList: JSON.stringify([{
					proId: this.evaluateInfo.productId,
					price: this.evaluateInfo.quotation,
					num: 1
				}]),
				recycleType: this.selectRecycle.recycleWay
			}
			const [res] = await this.$apis.getAllowCouponList(params)
			// const res = {
			// 	_data: {
			// 		couponsList: []
			// 	},
			// 	_errCode: '0'
			// }
			// if (this.selectRecycle.recycleWay === '3') {
			// 	res._data.couponsList.push({
			// 		couponsId: '111',
			// 		couponsValue: '50000',
			// 		couponsValidityBegin: '2023-08-30 16:00:00',
			// 		couponsValidity: '2023-11-20 16:00:00',
			// 		couponsName: '9月以旧换新',
			// 		couponsDesc: '',
			// 		minQuation: '500000',
			// 		isCanUse: '1',
			// 		desc: ''
			// 	})
			// }
			// if (this.selectRecycle.recycleWay === '2') {
			// 	res._data.couponsList.push({
			// 		couponsId: '111',
			// 		couponsValue: '40000',
			// 		couponsValidityBegin: '2023-08-25 10:00:00',
			// 		couponsValidity: '2023-11-20 10:00:00',
			// 		couponsName: '9月以旧换新',
			// 		couponsDesc: '',
			// 		minQuation: '500000',
			// 		isCanUse: '1',
			// 		desc: ''
			// 	})
			// }
			// if (this.selectRecycle.recycleWay === '1') {
			// 	res._data.couponsList.push({
			// 		couponsId: '111',
			// 		couponsValue: '30000',
			// 		couponsValidityBegin: '2023-08-23 23:15:00',
			// 		couponsValidity: '2023-11-20 23:15:00',
			// 		couponsName: '9月以旧换新',
			// 		couponsDesc: '',
			// 		minQuation: '500000',
			// 		isCanUse: '1',
			// 		desc: ''
			// 	})
			// }
			if (res._errCode === '0') {
				const list = res._data.couponsList || []
				list.forEach(item => {
					item.startDate = item.couponsValidityBegin.substring(0, 10).replace(/-/g, '.')
					item.endDate = item.couponsValidity.substring(0, 10).replace(/-/g, '.')
				})
				const selectRecycle = this.recycleWays.find(e => e.recycleWay === params.recycleType)
				if (selectRecycle) {
					this.discountInfo.all[selectRecycle.recycleKey] = list
				}
			}
			this.computedDiscounts()
		},
		/*
		 * 用户地址
		 * 包含顺丰邮寄、工程师上门、到店回收
		*/
		async getAllowAddressList (addrInfo) {
			const params = {
				recycleWay: this.selectRecycle.recycleWay
			}
			const [res] = await this.$apis.getAllowAddressList(params)
			if (res._errCode === '0') {
				const list = res._data.list || []
				const selectRecycle = this.recycleWays.find(e => e.recycleWay === params.recycleWay)
				if (selectRecycle) {
					this.addressInfo.all[selectRecycle.recycleKey] = list
				}
				if (addrInfo) {
					this.addressInfo.recycleWay = ''
					const validAddrInfo = list.find(item => {
						return item.addrId === addrInfo.addrId && item.status === '1' && Boolean(item.latitude) && Boolean(item.longitude)
					})
					if (validAddrInfo) {
						this.chooseAddress(validAddrInfo)
					}
				} else {
					this.setHistoryAddress()
				}
			}
		},
		/*
		 * 门店列表
		*/
		async getStoreList () {
			const { latitude, longitude, address = {} } = this.userLocation
			const { cityId } = this.userSelectLocation
			const params = {
				latitude: latitude || '-1',
				longitude: longitude || '-1',
				pageIndex: '1',
				pageSize: '1'
			}
			if (cityId || address.cityCode) {
				params.areaId = cityId || address.cityCode
			}
			const [res] = await this.$apis.getStoreList(params)
			if (res._errCode === '0') {
				const storeList = res._data.storeList || []
				storeList.forEach(item => {
					item.distances = computedDistance(item.distance || '')
				})
				this.currentStore = storeList[0] || {}
			}
		},
		/*
		 * 价格趋势
		*/
		async getPriceHistory () {
			const [res] = await this.$apis.getPriceHistory({
				productId: this.evaluateInfo.productId,
				price: this.evaluateInfo.quotation
			})
			if (res._errCode === '0') {
				this.priceHistory = res._data || []
			}
		},
		/*
		 * 机型SKU信息
		*/
		async getEvaluateSkuResult () {
			const [res] = await this.$apis.getEvaluateSkuResult({
				evaluateid: this.evaluateInfo.evaluateid
			})
			if (res._errCode === '0') {
				this.productSkuList = res._data || []
			}
		},
		/*
		 * 挽留信息
		*/
		async getBulletInfo () {
			const [res] = await this.$apis.getBulletInfo()
			if (res._errCode === '0') {
				this.bulletInfo = res._data || {}
			}
		},
		/*
		 * 挽留信息
		*/
		async getShareInfo () {
			const [res] = await this.$apis.getShareInfo()
			if (res._errCode === '0') {
				this.singleShareInfo = res._data || {}
			}
		},
		/*
		 * 重新估价
		*/
		afreshEvaluate () {
			const routers = getCurrentPages()
			const prevRouter = routers[routers.length - 2]
			if (prevRouter && prevRouter.route === 'pages/evaluate/index') {
				return uni.navigateBack()
			}
			const productId = this.evaluateInfo.productId || this.productId
			if (productId) {
				uni.redirectTo({
					url: `/pages/evaluate/index?productId=${productId}`
				})
			} else {
				uni.redirectTo({
					url: '/pages/products/index'
				})
			}
		},
		/*
		 * 默认选中历史地址
		*/
		setHistoryAddress () {
			const addrKey = this.selectRecycle.recycleKey
			const localAddress = uni.getStorageSync(`hsb_user_address_${addrKey}`)
			if (typeof localAddress === 'object') {
				this.addressInfo.selected[addrKey] = this.addressInfo.all[addrKey].find(e => {
					return e.addrId === localAddress.addrId && e.status === '1' && Boolean(e.latitude) && Boolean(e.longitude)
				}) || {}
			}
		},
		/*
		 * 满加/优惠券累加
		 * 根据回收方式来计算
		*/
		computedDiscounts () {
			const typeActivityList = this.evaluateInfo.typeActivityList || []
			const couponList = this.discountInfo.all[this.selectRecycle.recycleKey] || []
			this.discountInfo.selected = {
				addConpous: typeActivityList.find(e => {
					return e.recycleType === this.selectRecycle.recycleWay
				}) || {},
				useConpous: couponList.find(e => {
					return e.isCanUse === '1'
				}) || {}
			}
		},
		/*
		 * 切换回收方式
		*/
		recycleChange (recycleInfo) {
			this.selectRecycle = recycleInfo
			this.getAllowAddressList()
			if (this.discountInfo.all[this.selectRecycle.recycleKey].length > 0) {
				return this.computedDiscounts()
			}
			this.discountInfo.selected = { addConpous: {}, useConpous: {} }
			this.getAllowCouponList()
		},
		/*
		 * 拉起时间Picker
		*/
		dateChange () {
			const recycleWay = this.selectRecycle.recycleWay
			if (this.dateInfo.recycleWay !== recycleWay) {
				this.dateInfo.recycleWay = recycleWay
				this.dateInfo.list = JSON.parse(JSON.stringify(this.dateInfo.all[this.selectRecycle.recycleKey] || []))
			}
			this.$refs.datePickerCom.open()
		},
		/*
		 * 拉起地址Picker
		*/
		addressChange () {
			const recycleWay = this.selectRecycle.recycleWay
			if (this.addressInfo.recycleWay !== recycleWay) {
				this.addressInfo.recycleWay = this.selectRecycle.recycleWay
				this.addressInfo.list = JSON.parse(JSON.stringify(this.addressInfo.all[this.selectRecycle.recycleKey] || []))
			}
			this.$refs.recycleAddressCom.open()
		},
		/*
		 * 选择时间
		*/
		chooseDate (list) {
			if (list.length === 2) {
				this.dateInfo.selected[this.selectRecycle.recycleKey] = list.map(e => e.time)
			}
		},
		/*
		 * 选择地址
		*/
		chooseAddress (addrInfo) {
			this.addressInfo.selected[this.selectRecycle.recycleKey] = addrInfo
			uni.setStorage({
				key: `hsb_user_address_${this.selectRecycle.recycleKey}`,
				data: addrInfo
			})
		},
		/*
		 * 新增/编辑地址
		*/
		manageAddress (addrInfo) {
			const params = {
				recycleWay: this.selectRecycle.recycleWay
			}
			if (addrInfo.addrId) {
				params.addrId = addrInfo.addrId
			}
			uni.navigateTo({
				url: `/pages/address/recycle-save/index?${queryString.stringify(params)}`,
				events: {
					saveAddressInfo: (addrInfo) => {
						this.getAllowAddressList(addrInfo.data)
					}
				}
			})
		},
		/*
		 * 选择/更换地址
		*/
		chooseStore () {
			uni.navigateTo({
				url: `/pages/store/list/index?cityId=${this.currentStore.cityId || ''}`,
				events: {
					saveStoreInfo: (storeInfo) => {
						this.currentStore = storeInfo.data || {}
					}
				}
			})
		},
		/*
		 * 开通信用预付
		 * 只有支付宝小程序可用，但需要定义函数，否则会报错函数不存在
		*/
		beforeOpenCredit (e) {
			// #ifdef MP-ALIPAY
			this.openCredit(e)
			// #endif
		},
		/*
		 * 切换是否预付
		 * 只有支付宝小程序可用，但需要定义函数，否则会报错函数不存在
		*/
		beforeChangePrepay (e) {
			// #ifdef MP-ALIPAY
			this.changePrepay(e)
			// #endif
		},
		/*
		 * 检验下单参数
		*/
		checkPlaceOrderParams () {
			const params = {
				payType: '27',
				evaluateid: this.evaluateInfo.evaluateid,
				recycleType: this.selectRecycle.recycleType
			}
			const recycle = {
				store: () => {
					if (!this.currentStore.storeId) {
						return uni.showToast({
							title: '请选择门店',
							icon: 'none'
						})
					}
					if (this.dateInfo.selected.store.length === 0) {
						return uni.showToast({
							title: '请选择到店时间',
							icon: 'none'
						})
					}
					if (!/^1[3456789]\d{9}$/.test(this.phoneNumber)) {
						return uni.showToast({
							title: '请输入11位手机号码',
							icon: 'none'
						})
					}
					params.storeId = this.currentStore.storeId
					params.time = this.dateInfo.selected.store.join(' ')
					params.tel = this.phoneNumber
					this.placeOrder(params)
				},
				sf: () => {
					if (!this.addressInfo.selected.sf.addrId) {
						return uni.showToast({
							title: '请选择上门地址',
							icon: 'none'
						})
					}
					if (this.dateInfo.selected.sf.length === 0) {
						return uni.showToast({
							title: '请选择取件时间',
							icon: 'none'
						})
					}
					// #ifdef WEB
					if (!this.account || !this.accountName) {
						return uni.showToast({
							title: '请输入支付宝账户收款信息',
							icon: 'none'
						})
					}
					if (
						!/^(1[3-9][0-9])\d{8}$/.test(this.account) &&
						!/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(this.account)
					) {
						return uni.showToast({
							title: '支付宝账号请输入正确的手机号或邮箱地址',
							icon: 'none'
						})
					}
					params.payName = this.accountName
					params.payAccount = this.account
					// #endif
					// #ifdef WEB || MP-ALIPAY
					params.payType = '2'
					// #endif
					// #ifndef WEB || MP-ALIPAY
					params.payType = '26'
					// #endif
					params.time = this.dateInfo.selected.sf.join(' ')
					Object.assign(params, this.getAddressParams('sf'))
					this.placeOrder(params)
				},
				visit: () => {
					if (!this.addressInfo.selected.visit.addrId) {
						return uni.showToast({
							title: '请选择上门地址',
							icon: 'none'
						})
					}
					if (this.dateInfo.selected.visit.length === 0) {
						return uni.showToast({
							title: '请选择上门时间',
							icon: 'none'
						})
					}
					Object.assign(params, this.getAddressParams('visit'))
					params.time = this.dateInfo.selected.visit.join(' ')
					this.placeOrder(params)
				},
				sxx: () => {
					if (!this.addressInfo.selected.sxx.addrId) {
						return uni.showToast({
							title: '请选择上门地址',
							icon: 'none'
						})
					}
					if (this.dateInfo.selected.sxx.length === 0) {
						return uni.showToast({
							title: '请选择上门时间',
							icon: 'none'
						})
					}
					Object.assign(params, this.getAddressParams('sxx'))
					params.time = this.dateInfo.selected.sxx.join(' ')
					this.placeOrder(params)
				}
			}
			recycle[this.selectRecycle.recycleKey]()
		},
		/*
		 * 用户地址信息
		 * @param {String} recycleKey 回收标识
		*/
		getAddressParams (recycleKey) {
			const {
				userName,
				tel,
				provinceName,
				cityName,
				areaName,
				address,
				cityCode,
				areaCode,
				latitude,
				longitude
			} = this.addressInfo.selected[recycleKey] || {}
			return {
				userName,
				tel,
				province: provinceName,
				city: cityName,
				county: areaName || cityName || '',
				address,
				regionId: cityCode || areaCode || '',
				latitude,
				longitude
			}
		},
		/*
		 * 下单
		*/
		async placeOrder (params) {
			if (this.discountInfo.selected.addConpous.activityId) {
				params.activityId = this.discountInfo.selected.addConpous.activityId
			}
			if (this.discountInfo.selected.useConpous.couponsId) {
				params.couponId = this.discountInfo.selected.useConpous.couponsId
			}
			console.log(params)
			if (this.loading) return
			this.loading = true
			uni.showLoading({
				title: '提交中',
				mask: true
			})
			const { status, isPrepay } = this.creditInfo
			const [res] = await this.$apis[
				params.recycleType === '1' && status === '3' && isPrepay
				? 'createCreditOrder'
				: 'createOrder'
			](params)
			this.loading = false
			uni.hideLoading()
			if (res._errCode === '0') {
				uni.redirectTo({
					url: `/pages/order/result/index?orderNum=${res._data.orderNum}`
				})
			} else {
				uni.showToast({
					title: res._errStr || '下单失败',
					icon: 'none'
				})
			}
		},
	},
	onHide () {
		this.$refs.evaluateCardCom.clearAllInterval()
	},
	onUnload () {
		this.$refs.evaluateCardCom.clearAllInterval()
	},
	onShow () {
		if (this.$refs.evaluateCardCom) {
			this.$refs.evaluateCardCom.computedCountdown()
		}
		// #ifdef MP-ALIPAY
		if (this.creditInfo.creditAction) {
			this.creditInfo.creditAction = false
			this.checkCreditStatusByOutNo()
		}
		// #endif
	},
	onLoad (options) {
		this.productId = options.productId || ''
		this.evaluateId = options.evaluateId || ''
		this.initData()
	}
}
</script>

<style lang="scss" scoped>
.create-page {
	position: relative;
	min-height: 100%;
	background-color: #ffffff;
}
</style>
